<?php 

/**
 * 设置菜单配置
 */

include_once './debug.php';
include_once './function.php';
include_once './access_token.php';

define('MENU_PATH', './menu.txt');


if (array_key_exists('option', $_GET)) {
    $option = $_GET['option'];
} else {
    $option = 'option';
}

MenuItem::option($option);

/**
 * 获取menu
 */
class MenuItem
{
    /**
     * 获取菜单字符串
     */
    static public function setMenu()
    {
        $url  = 'https://api.weixin.qq.com/cgi-bin/menu/create?';
        $url .= 'access_token='.AccessToken::getToken();
        $menu = file_get_contents(MENU_PATH);
        $rest = post($url, $menu);
        if ($rest['errcode'] != 0) {
            de("\n---------------\n".json_encode($rest)."\n");
            return false;
        }
        return true;
    }

    /**
     * 删除菜单
     */
    static public function clearMenu()
    {
        $url  = 'https://api.weixin.qq.com/cgi-bin/menu/delete?';
        $url .= 'access_token='.AccessToken::getToken();
        $rest = post($url, null, false);
        if ($rest['errcode'] != 0) {
            de("\n---------------\n".json_encode($rest)."\n");
            return false;
        }
        return true;
    }

    /**
     * 显示选项
     */
    static public function option($option)
    {
        switch ($option) {
            case 'set':
                $ret = static::setMenu();
                break;
            
            case 'clear':
                $ret = static::clearMenu();
                break;

            default:
                break;
        }

        if (isset($ret)) {
            echo('处理结果是<br>');
            var_dump($ret);
            echo '<br>';
        }
        static::index();
    }

    /**
     * 构建菜单选项
     */
    static public function index()
    {
        $url = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
        echo '<a href="http://'.$url.'?option=set">设置菜单选择</a><br>';
        echo '<a href="http://'.$url.'?option=clear">清空菜单选择</a><br>';
    }
}